package org.example.controller;

import jakarta.validation.constraints.Pattern;
import org.example.mapper.CompanyMapper;
import org.example.mapper.UserMapper;
import org.example.pojo.*;
import org.example.service.*;
import org.example.utils.JWTUtil;
import org.example.utils.ThreadLocalUtil;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private ResumeService resumeService;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private PersonalmessageService personalmessageService;

    @Autowired
    private CompanymessageService companymessageService;

    @Autowired
    private JobService jobService;

    @PostMapping("/user/register")
    public Result Register(@Pattern(regexp = "^\\S{5,16}") String username, @Pattern(regexp = "^\\S{5,16}") String password, @Pattern(regexp = "^\\S{5,16}") String repassword, String phone) {
        User user = userMapper.selectOneUser(username);
        if (user != null) {
            return Result.error("用户名已存在");
        } else if (!password.equals(repassword)) {
            return Result.error("两次密码不一致");
        } else {
            User newUser = new User();
            newUser.setUsername(username);
            newUser.setPassword(password);
            newUser.setPhone(phone);
            userMapper.insertUser(newUser);
            return Result.success("注册成功");
        }
    }


    @PostMapping("/user/login")
    public Result Login(@Pattern(regexp = "^\\S{5,16}") String username, @Pattern(regexp = "^\\S{5,16}") String password) {
        User user = userMapper.selectOneUser(username);
        if (user != null) {
            if(user.getPassword().equals(password)){
                //保存token
                Map<String, Object> claim = new HashMap<>();
                claim.put("id",user.getId());
                claim.put("username", user.getUsername());
                claim.put("password", user.getPassword());
                String token = JWTUtil.getToken(claim);
                return Result.success(token);
            }
            else{
                return Result.error("密码错误");
            }
        } else {
            return Result.error("用户名不存在");
        }
    }

    @PostMapping("/user/allUsers")
    public Result<PageBean<Resume>> getAllUsers(Integer userId, String name,Integer pageNum, Integer pageSize) {
        PageBean<Resume> pb = resumeService.list(userId, name, pageNum, pageSize);
        return Result.success(pb);
    }


    //获取当前用户信息
    @GetMapping("/user/userInfo")
    public Result<User> UserInfo(){
        //从ThreadLocal中获取数据
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");

        User user = userService.findByUserName(userId);
        return Result.success(user);
    }

    //用户发送验证码进行密码修改
    @PostMapping("/user/forgetPassword")
    public Result<String> forgetPassword(String phone) throws Exception {
        //发送验证码
        String code =userService.sendCode(phone);
        return Result.success(code);
    }

    //用户修改密码
    @PostMapping("/user/updatePassword")
    public Result<String> changePassword(String code, String mycode, String username, String phone, String password) throws Exception {
        if (!code.equals(mycode)){
            return Result.error("验证码错误");
        }
        //修改密码
        userService.updatePassword(username, phone, password);
        return Result.success("密码修改成功");
    }

    //用户引导页面功能
    @PostMapping("/user/person/guide")
    public Result<String> PersonGuide(@RequestBody Resume resume) {
        //从ThreadLocal中获取数据
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        //更新用户的引导页面状态以及更新为平台用户
        userService.updateStatus(0, 1, 0, userId);

        //查询用户电话号码
        String phone = userMapper.findByUserId(userId).getPhone();
        resume.setPhone(phone);
        //插入简历信息，变化id
        resume.setUserId(userId);
        String birth = resume.getBirthdate().substring(0, 10);
        System.out.println(birth);
        resume.setBirthdate(birth);
        String intention = resume.getIntention();
        String new_intention = intention.split("-")[1];
        resume.setIntention(new_intention);
        //引导页面功能
        resumeService.insertResume(resume);
        return Result.success();
    }

    //企业用户引导页面功能
    @PostMapping("/user/company/guide")
    public Result<String> CompanyGuide(@RequestBody Company company) {
        //从ThreadLocal中获取数据
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");

        //插入企业信息，设置id为当前表中的最大值
        Integer companyId = userService.selectMaxId() + 1;
        //更新用户的引导页面状态以及更新为平台用户,并且增加公司id
        userService.updateStatus(1, 1, companyId, userId);

        company.setCompanyId(companyId);
        //引导页面功能
        companyService.insertCompany(company);
        return Result.success();
    }

    //检查企业名称是否存在
    @PostMapping("/user/checkCompanyName")
    public Result<List<Company>> checkCompanyName(String companyName) {
        List<Company> companys = companyService.selectCompanyByName(companyName);
        return Result.success(companys);
    }

    //用户个人中心信息获取接口
    @GetMapping("/user/person/info")
    public Result<UserDto> PersonInfo() {
        //从ThreadLocal中获取数据
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");

        //用户信息转接
        UserDto userDto = new UserDto();
        User user = userService.findByUserName(userId);
        userDto.setUser(user);
        //查找用户简历信息
        Resume resume = resumeService.selectByUserId(userId);
        userDto.setResume(resume);

        return Result.success(userDto);
    }

    //用户投递信息获取接口
    @GetMapping("/user/person/JobInfo")
    public Result<UserJobDto> PersonDelivery() {
        //从ThreadLocal中获取数据
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");

        //用户信息转接
        UserJobDto userJobDto = new UserJobDto();
        userJobDto.setUserId(userId);

        //获取用户所有的职位信息
        List<Personalmessage> personalmessages = personalmessageService.selectByUserId(userId);
        //用户收藏的职位集合
        List<Job> CollectJobList = new ArrayList<>();
        //用户投递的职位集合
        List<Job> PostJobList = new ArrayList<>();
        //用户收到面试邀请的职位集合
        List<Job> RecruitJobList = new ArrayList<>();


        for (Personalmessage personalmessage :personalmessages) {
            if(personalmessage.getMyFavorId() != null){
                //获取用户收藏的职位
                Job collectJob = jobService.selectByJobId(personalmessage.getMyFavorId(), personalmessage.getCompanyId());
                CollectJobList.add(collectJob);
            }
            if(personalmessage.getPostId() != null){
                //获取用户投递的职位
                Job postJob = jobService.selectByJobId(personalmessage.getPostId(), personalmessage.getCompanyId());
                PostJobList.add(postJob);
            }
            if(personalmessage.getGetpostId() != null){
                //获取用户收到面试邀请的职位
                Job recruitJob = jobService.selectByJobId(personalmessage.getGetpostId(), personalmessage.getCompanyId());
                RecruitJobList.add(recruitJob);
            }
        }

        //返回给前端的数据
        userJobDto.setCollectJobList(CollectJobList);
        userJobDto.setPostJobList(PostJobList);
        userJobDto.setRecruitJobList(RecruitJobList);

        return Result.success(userJobDto);
    }

    //删除收藏的岗位信息
    @PostMapping("/user/removeCollectJob")
    public Result removeCollectJob(Integer jobId, Integer companyId){
        //找到用户id
        //从ThreadLocal中获取数据
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");

        //将收藏岗位的id更新为null
        personalmessageService.removeCollectJob(userId, jobId, companyId);
        return Result.success();
    }

    //删除投递的岗位信息
    @PostMapping("/user/removePostJob")
    public Result removePostJob(Integer jobId, Integer companyId){
        //找到用户对应的消息
        //从ThreadLocal中获取数据
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        //将投递岗位的id更新为null
        personalmessageService.removePostJob(userId, jobId, companyId);
        return Result.success();
    }

    //删除被邀请的岗位信息
    @PostMapping("/user/removeRecruitJob")
    public Result removeRecruitJob(Integer jobId, Integer companyId){
        //找到用户对应的消息
        //从ThreadLocal中获取数据
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        //将投递岗位的id更新为null
        personalmessageService.removeRecruitJob(userId, jobId, companyId);
        return Result.success();
    }


    //用户修改个人信息接口
    @PostMapping("/user/person/updateInfo")
    public Result updatePersonInfo(@RequestBody Resume resume) {
        //从ThreadLocal中获取数据
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");

        //修改个人信息
        userService.updateUser(resume.getPhone(), userId);
        //修改简历信息
        resume.setUserId(userId);
        resumeService.updateResume(resume);
        return Result.success();
    }

    //修改企业信息接口
    @PostMapping("/user/company/updateInfo")
    public Result updateCompanyInfo(@RequestBody Company company) {
        //修改企业信息
        companyService.updateCompany(company);
        //修改职位中的企业信息
        jobService.updateCompany(company);
        return Result.success();
    }

    //用户更新头像信息接口
    @PatchMapping("/user/headImg")
    public Result<String> updateHeadImg(@RequestParam("headImg") @URL String headImg){ //@URL校验传过来的要是一个url地址格式
        //从ThreadLocal中获取数据
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        userService.updateHeadImg(headImg, userId);
        return Result.success();
    }

    //升级用户为管理员
    @PostMapping("/user/upgrade")
    public Result<String> upgrade(Integer userId) {
        //更新用户状态为管理员
        userService.upgradeUser(userId, 2);
        resumeService.updateStatus(userId, 2);
        return Result.success("升级成功");
    }

    //获取公司用户信息
    @GetMapping("/user/company/userInfo")
    public Result<Company> CompanyInfo() {
        //从ThreadLocal中获取数据
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        User user = userService.findByUserName(userId);

        //获取公司信息
        Company company = companyService.selectByCompanyId(user.getCompanyId());
        return Result.success(company);
    }

    //更新用户收到的面试邀请
    @PostMapping("/user/updatePersonMessage")
    public Result updateInterview(Integer jobId, Integer companyId, Integer resumeId, Integer approve){
        Resume resume = resumeService.selectByResumeId(resumeId);
        Companymessage companymessage = companymessageService.selectStatus(resume.getUserId(), jobId, companyId);
        if(companymessage != null){
            //更新用户收到的面试邀请
            personalmessageService.updateInterview(jobId, companyId, resumeId, approve);
            //更新公司邀请状态
            companymessageService.updateInviteStatus(jobId, companyId, resumeId, approve);
        }else{
            personalmessageService.insertPersonalApproveMessage(resume.getUserId(), companyId, jobId, resumeId);
            companymessageService.insertCompanyApproveMessage(resume.getUserId(), companyId, jobId, resumeId);
        }

        return Result.success();
    }

    //根据用户Id获取简历信息
    @PostMapping("/user/getResumeId")
    public Result<Resume> getResumeId(Integer userId){
        Resume resume = resumeService.selectByUserId(userId);
        return Result.success(resume);
    }
}
